package com.wgo.bpot.server.servicewrapper;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import com.wgo.bpot.domain.common.CrudOperation;
import com.wgo.bpot.domain.common.Service;
import com.wgo.bpot.domain.common.ServicePrivilege;
import com.wgo.bpot.domain.common.UserRole;
import com.wgo.bpot.domain.common.impl.UserRoleImpl;

public enum DummyRoles implements UserRole {
	ADMIN("admin","getServerTime","retrieveRootSystem","createDbSchema"),USER("user");

	private UserRole userRole;
	
	private DummyRoles(String name, String... serviceNames){
		userRole = new UserRoleImpl(name);
        if ((null == serviceNames) || (0 == serviceNames.length)) {
            userRole.addServicePrivilege(new DummyPrivilege("NONE"));
        } else for (String serviceName : serviceNames) {
            userRole.addServicePrivilege(new DummyPrivilege(serviceName));
        }
	}
	
	public void addNestedUserRole(UserRole userRole) {
		userRole.addNestedUserRole(userRole);
	}

	public String getName() {
		return userRole.getName();
	}

	public Set<UserRole> getNestedUserRoles() {
		return userRole.getNestedUserRoles();
	}

	public void removeNestedUserRole(UserRole userRole) {
		userRole.removeNestedUserRole(userRole);
	}

	public void setName(String name) {
		userRole.setName(name);
	}

    public void addServicePrivilege(ServicePrivilege servicePrivilege) {
        userRole.addServicePrivilege(servicePrivilege);
    }

//    public <T> boolean isAllowedIfApplicable(Service service, CrudOperation operation, Class<T> conceptType, T conceptInstance) {
//        return userRole.isAllowedIfApplicable(service, operation, conceptType, conceptInstance);
//    }

    public void removeServicePrivilege(ServicePrivilege servicePrivilege) {
        userRole.removeServicePrivilege(servicePrivilege);
    }
    
    public Set<ServicePrivilege> getServicePriviliges() {
        return userRole.getServicePriviliges();
    }

    public boolean isAllowed(ServicePrivilege... servicePrivileges) {
        return userRole.isAllowed(servicePrivileges);
    }
    
    private class DummyPrivilege implements ServicePrivilege {
        private Set<String> allowedServices = new HashSet<String>();

        public DummyPrivilege(String... allowedServices){
            this.allowedServices = new HashSet<String>(Arrays.asList(allowedServices));;
        }
        
        public <T> boolean isApplicable(Service service, CrudOperation operation, Class<T> conceptType, T conceptInstance) {
            return null != service;
        }
        
        public <T> boolean isAllowed(Service service, CrudOperation operation, Class<T> conceptType, T conceptInstance) {
            return allowedServices.contains(service.getName());
        }

        public String getName() {
            return "DummyPrivilege";
        }
    }

}
